package com.suyl.tools.proxy.core.service.imp;

import com.suyl.tools.proxy.core.config.HttpProxyContext;
import com.suyl.tools.proxy.core.config.ProxyConfig;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.util.Iterator;
import java.util.List;

/**
 * @Author suyanlong
 * @Date 2020/6/14 17:47
 * @Version 1.0
 * @Description 解析xml代理路径
 */
@Component
public class HttpProxyXmlServiceImpl implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger log = LoggerFactory.getLogger(HttpProxyXmlServiceImpl.class);

    @Autowired
    private ProxyConfig proxyConfig;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent ev) {
        readHttpXmlProxyCfg();
    }

    private void readHttpXmlProxyCfg() {
        try {
            Resource res = new ClassPathResource("proxy-url.xml");
            parse(res.getURL());
        } catch (Exception e) {
            log.error("read xml cfg error", e);
        }
    }

    @SuppressWarnings("unchecked")
    private void parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        Element root = document.getRootElement();
        String ip = proxyConfig.getIp();
        Integer port = proxyConfig.getPort();
        List<Node> eles = root.selectNodes("/configuration/http");
        Iterator iterator = eles.iterator();
        String urlName = null;
        String urlPattern = null;
        String urlProxy = null;
        while (iterator.hasNext()) {
            Element httpEle = (Element) iterator.next();
            urlName = httpEle.selectSingleNode("url-name").getText();
            urlPattern = httpEle.selectSingleNode("url-pattern").getText();
            urlProxy = httpEle.selectSingleNode("url-proxy").getText();
            if (!StringUtils.isEmpty(urlPattern) && !StringUtils.isEmpty(urlProxy)) {
                urlProxy = "http://" + ip + ":" + port + urlProxy;
                HttpProxyContext.add(urlPattern, urlProxy);
            }
            if (log.isDebugEnabled()) {
                log.debug("url-name:" + urlName + ", url-pattern:" + urlPattern + ", url-proxy:" + urlProxy);
            }
        }
    }

}
